package com.bmob.lover.ui.fragment.cost

import android.animation.ValueAnimator
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemDragListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.theone.common.constant.BundleConstant
import com.theone.common.ext.getValueNonNull
import com.theone.common.ext.trimAll
import com.bmob.lover.R
import com.bmob.lover.data.constant.CostConstant
import com.bmob.lover.data.model.bean.CostCategory
import com.bmob.lover.ui.adapter.CostCategoryAdapter
import com.bmob.lover.ui.fragment.base.BasePagerFragment
import com.bmob.lover.viewmodel.request.CostCategoryRequestViewModel
import com.bmob.lover.viewmodel.request.CostCategoryUpdateViewModel
import com.theone.mvvm.ext.qmui.*

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-05-20 10:10
 * @describe TODO
 * @email 625805189@qq.com
 * @remark
 */
class CostCategoryFragment private constructor() :
    BasePagerFragment<CostCategory, CostCategoryRequestViewModel>() {

    companion object {
        fun newInstance(type: Int): CostCategoryFragment {
            return CostCategoryFragment().apply {
                arguments = Bundle().apply {
                    putInt(BundleConstant.TYPE, type)
                }
            }
        }
    }

    private val mUpdateVm: CostCategoryUpdateViewModel by viewModels()

    private val mType: Int by getValueNonNull(BundleConstant.TYPE)

    private var isChanged: Boolean = false

    private val mCategoryType: String by lazy {
        CostConstant.getCostCategoryType(mType)
    }

    override fun initView(root: View) {
        super.initView(root)
        setTitleWitchBackBtn(mCategoryType)
        getTopBar()?.addRightTextButton(R.string.save, R.id.topbar_right_text)?.setOnClickListener {
            update()
        }
    }

    override fun initData() {
        super.initData()
        getViewModel().type = mType
    }

    override fun createAdapter(): BaseQuickAdapter<CostCategory, *> = CostCategoryAdapter()

    override fun initAdapter() {
        super.initAdapter()
        getAdapter().isAnimationFirstOnly = true
        getAdapter().draggableModule.run {
            isDragEnabled = true
            isDragOnLongPressEnabled = false
            setOnItemDragListener(dragListener)
        }
    }

    private fun update() {
        val categories = getAdapter().data
        for ((index, item) in categories.withIndex()) {
            // 当前位置不一样，说明调换过位置了，需要更新
            if (!isChanged && item.name != getViewModel().getResponseLiveData().value?.get(index)?.name) {
                isChanged = true
            }
            item.orderCode = index
        }
        if (isChanged) {
            mUpdateVm.batchUpdate(categories)
        } else {
            showFailTipsDialog("丝毫没有改变啥")
        }
    }

    override fun createObserver() {
        addLoadingObserve(mUpdateVm)
        super.createObserver()
        mUpdateVm.run {
            getBatchSuccessLiveDate().observe(this@CostCategoryFragment, Observer {
                mEventVm.onPublishSuccess(mCategoryType)
                showSuccessTipsExitDialog("更新成功")
            })

            getErrorLiveData().observe(this@CostCategoryFragment, Observer {
                showFailTipsDialog(it)
            })
        }
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val category = adapter.getItem(position) as CostCategory
        context?.showEditDialog(
            "修改名称",
            category.name,
            "类别名称",
            listener = object : QMUIEditDialogListener {
                override fun onEditDialogClick(
                    dialog: QMUIDialog,
                    content: String,
                    index: Int
                ) {
                    dialog.dismiss()
                    val name = content.trimAll()
                    if (index > 0 && name.isNotEmpty()) {
                        if (content.length > 4) {
                            showFailTipsDialog("类别名称不能超过四个字")
                        } else {
                            getAdapter().data.let {
                                for (item in it) {
                                    if (item.name == name) {
                                        showFailTipsDialog("类别已存在")
                                        return
                                    }
                                }
                                category.name = name
                                getAdapter().notifyItemChanged(position)
                                isChanged = true
                            }
                        }
                    }
                }
            })
    }

    private val dragListener: OnItemDragListener = object : OnItemDragListener {

        override fun onItemDragMoving(
            source: RecyclerView.ViewHolder?,
            from: Int,
            target: RecyclerView.ViewHolder?,
            to: Int
        ) {

        }

        override fun onItemDragStart(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
            val holder = viewHolder as BaseViewHolder
            // 开始时，item背景色变化，demo这里使用了一个动画渐变，使得自然
            val startColor = Color.WHITE
            val endColor = Color.rgb(245, 245, 245)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                val v = ValueAnimator.ofArgb(startColor, endColor)
                v.addUpdateListener { animation: ValueAnimator ->
                    holder.itemView.setBackgroundColor(
                        animation.animatedValue as Int
                    )
                }
                v.duration = 300
                v.start()
            }
        }

        override fun onItemDragEnd(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
            val holder = viewHolder as BaseViewHolder
            // 结束时，item背景色变化，demo这里使用了一个动画渐变，使得自然
            val startColor = Color.rgb(245, 245, 245)
            val endColor = Color.WHITE
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                val v = ValueAnimator.ofArgb(startColor, endColor)
                v.addUpdateListener { animation: ValueAnimator ->
                    holder.itemView.setBackgroundColor(
                        animation.animatedValue as Int
                    )
                }
                v.duration = 300
                v.start()
            }
        }

    }
}